package xyz.yang.persistence.mongo.core.multipletenant;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import xyz.yang.toodles.ThreadLocalUtil;

/**
 * @author Xuehong Yang
 * @since 1.0
 */

@Slf4j
public class SimpleMongoClientMultiDatabaseFactory extends SimpleMongoClientDatabaseFactory {
    public SimpleMongoClientMultiDatabaseFactory(MongoClient mongoClient, String databaseName) {
        super(mongoClient, databaseName);
    }

    @Override
    protected MongoDatabase doGetMongoDatabase(String dbName) {
        String tenantDatabase = ThreadLocalUtil.get("X-Tenant", dbName);
        log.info("Switching the database: {}", tenantDatabase);
        return super.doGetMongoDatabase(tenantDatabase);
    }
}
